import Vue from "vue";
import VueRouter from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false });
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "login"
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/login.vue"),
    meta: {
      title: "登陆",
      requireAuth: false
    },
  },
  {
    path: "/employeeList",
    name: "employeeList",
    component: () => import("@/views/employeeList.vue"),
    meta: {
      title: "员工列表",
      requireAuth: true
    },
  },
  {
    path: "/employeeDetail",
    name: "employeeDetail",
    component: () => import("@/views/employeeDetail.vue"),
    meta: {
      title: "员工详情",
      requireAuth: true
    },
  },
  {
    path: "*",
    name: "error",
    component: () => import("@/views/error/index.vue")
  }
];

const router = new VueRouter({
  // mode: "history", // 去掉url中的#
  scrollBehavior: () => ({ y: 0 }),
  routes
});

router.beforeEach((to, from, next) => {
  NProgress.start();
  let title = to.meta.title || to.name;
  document.title = title;
  let token = localStorage.getItem('_token_')
  // 判断路由是否需要登录权限
  if (to.meta.requireAuth && !token) {
    localStorage.setItem("_redirect",to.fullPath)
    NProgress.done();
    next({
      path: `/login`
    });
  } else {
    next();
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
